<?php
/**
 * 作用：评论业务处理
 * 作者: shijy@soe-soe.com
 * 日期: 2016/4/26 21:05
 * 公司: 浙江宣逸网络科技有限公司<www.soe-soe.com>
 */
namespace Common\Model;
class CommentModel extends BaseModel{
	const FIX_USER_ALL    			=0;//不限发贴人
	const FIX_USER_SPECIFY         =1;//限定
	const FIX_USER_DEBAR        	=2;//排除


	/**
	 * 获取对象评论信息，
	 * Author: shijy
	 * @param $objType
	 * @param $objId
	 * @param int $uid
	 * @return array(
			count:评论数
	        done:指定uid有无进行点赞，0否，1是，2未知
	 * )
	 */
	public static function getCommentState($objType,$objId,$uid=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		if(!$objType || !$objId){
			return $dataFailure;
		}
		$M=M("comment_{$objType}",null,DB_MAIN_CFG);
		$done=0;
		if($uid){
			$done=$M->where('objType='.$objType.' and objID='.$objId.' and uid='.$uid)->find()?1:0;
		}
		$count=$M->where('objType='.$objType.' and objID='.$objId )->count();
		$dataSuccess['done']=$done;
		$dataSuccess['count']=$count;
		return $dataSuccess;
	}


	/**
	 * 获取评论列表数据,带分页信息
	 * Author: shijy
	 * @param $objType
	 * @param $objId
	 * @param $page
	 * @param int $pageSize
	 * @param int $fixUser,是否限定发起人
	 * @param int $uid,用户编号
	 * @return array
	 */
	public static function getCommentList($objType,$objId,$page,$pageSize=10,$fixUser=self::FIX_USER_ALL,$uid=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if(!$objType || !$objId){
			return $dataFailure;
		}
		$M=M("comment_{$objType}",null,DB_MAIN_CFG);
		$where = 'objType='.$objType.' and objID='.$objId.' and parentID=0 and isDisabled=0';
		if($uid) {
			switch ($fixUser) {
				case self::FIX_USER_ALL:
					break;
				case self::FIX_USER_SPECIFY:
					$where .= " and uid={$uid}";
					break;
				case self::FIX_USER_DEBAR:
					$where .= " and uid<>{$uid}";
					break;
			}
		}

		$rowCount=$M->where($where)->count();

		$pageCount=max(1,ceil($rowCount/$pageSize));
		$page=min(max($page,1),$pageCount);
		$offset=($page-1) * $pageSize;

		$order = 'praiseNum DESC,addTime DESC';

		$list=$M->where($where)->order($order)->limit($offset,$pageSize)->select();

		if($objType == OBJ_TYPE_ARTICLE || $objType == OBJ_TYPE_ACTIVITY){//文章，活动的评论才可点赞
			$commentPraiseType = OBJ_TYPE_COMMENT_ARTICLE;
			if($objType == OBJ_TYPE_ACTIVITY) $commentPraiseType = OBJ_TYPE_COMMENT_ACTIVITY;
			$uid = session("uid")+0;
			$commentObj = M('praise_log',null,DB_MAIN_CFG)->where("objType= {$commentPraiseType} and uid={$uid}")->getField("objID",true);
			if($commentObj){
				foreach($list as $key => $val){
					foreach($commentObj as $id){
						if($id == $val['id']){
							$list[$key]['praiseComment']=1;
							break;
						}
					}
				}
			}
		}

		if(count($list)>0){
			////////获取子评论，评论的评论////////
			$whereA=array();
			foreach($list as $k=>$v){
				$whereA[]=$v['id'];
				$list[$k]['content'] = raEmotionsUrl($v['content']);
			}
			$whereStr='objType='.$objType.' and objID='.$objId.' and parentID in ('.implode(',',$whereA).') and isDisabled=0';
			$children=$M->where($whereStr)->order('id asc')->select();
			foreach($children as $item){
				foreach($list as $k=>$v){
					if(!array_key_exists('children',$list[$k])){
						$list[$k]['children']=array();
					}
					if($item['objType']==$v['objType'] && $item['parentID']==$v['id']){
						$item['content'] = raEmotionsUrl($item['content']);
						$list[$k]['children'][]=$item;
					}
				}
			}
		}
		///////////////////////////////////////////////////
		$dataSuccess['id']	=$objId;
		$dataSuccess['type']	=$objType;
		$dataSuccess['total']	=$rowCount;
		$dataSuccess['totalPage']=$pageCount;
		$dataSuccess['page']	=$page;
		$dataSuccess['nextPage'] = $page >= $pageCount ? 0 : 1;//是有有下一页
		$dataSuccess['list']	=$list;
		return $dataSuccess;
	}



	/**
	 * 获取最新指定条数的评论
	 * Author: shijy
	 * @param $objType
	 * @param $objId
	 * @param int $pageSize
	 * @param int $fixUser,是否限定发起人
	 * @param int $uid,用户编号
	 * @return array
	 */
	public static function getCommentTop($objType,$objId,$pageSize=10,$fixUser=self::FIX_USER_ALL,$uid=0){
		return self::getCommentList($objType,$objId,1,$pageSize,$fixUser,$uid);
	}





	 /**
	 * 添加评论通用函数
	 * Author: shijy
	 * @param $objType
	 * @param $objID
	 * @param $parentID
	 * @param $content
	 * @param $userinfo
	 * @param $flag 标志是否加喜爱指数（活动报名留言不加喜爱指数）
	 * @param $albumstr 评论附图
	 * @return mixed
	 */
     public static function commentNew($objType,$objID,$parentID,$content,&$userinfo,$flag=1,$albumstr=''){
		 $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		 $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		 $content=strip_tags(preg_replace('/@.*:/','',$content));
		 if(!$objType || !$objID ){
			 return $dataFailure;
		 }
		 if(UtilsModel::strlen($content)<1){
			 $dataFailure['msg']="请输入评论内容";
			 return $dataFailure;
		 }

		 if(true !== $maskStr = checkCleanWord($content) ){
			 $dataFailure['msg'] = "评论内容中不能包含:".$maskStr;
			 return $dataFailure;
		 }

		 $table=C('OBJ_TABLE');
		 $table=$table[$objType];
		 $contentType=0;

		//评论列表
		$commentM=M('comment_'.$objType,null,DB_MAIN_CFG);
		$newData=array(
			'parentID'	=>$parentID,
			'objType'	=>$objType,
			'objID'		=>$objID,
			'objContentType'=>$contentType,
			'content'		=>$content,
			'uid'			=>$userinfo['uid'],
			'nickname'		=>$userinfo['nickname'],
			'addTime'		=>time()
		);
		 if (strlen($albumstr)>0){
			 $newData['album']=$albumstr;
		 }
		$result = $commentM->add($newData);
		if($result===false){
			$dataFailure['msg'] = "添加失败";
			return $dataFailure;
		}

		 //给客服推送消息
		 if($objType==OBJ_TYPE_STORE){
			 BusinessModel::sendTemplateMsg_Comment($objID,$content);
		 }



		 //评论文章发布通知
		 if($objType==OBJ_TYPE_ARTICLE){
			 $articleInfo=M('article',null,DB_MAIN_CFG)->where("id={$objID}")->find();
			 NoticeModel::saveNotice(NoticeModel::NOTICE_TYPE_COMMENT,$objType,$objID,$userinfo['uid'],$articleInfo['uid'],$articleInfo['title']);
		 }

		//增加对象的评论数
		 M($table, null, DB_MAIN_CFG)->where("id={$objID}")->setInc('commentNum');


		 if ($objType == OBJ_TYPE_TOY_RECORD) {
			 //评论得积分
			 $ret = UserModel::addUserValByAction($userinfo['uid'], OPT_COMMENT_TOY);
		 }else{
			 $ret = UserModel::addUserValByAction($userinfo['uid'], OPT_COMMENT);
		 }



		 if($ret['status']==0){
			 //$ret['tip']=S('tip_'.$userinfo['uid']);
			 S('tip_'.$userinfo['uid'],null);
			 return $ret;
		 }
		 return $dataSuccess;
	}
}